import { Toast } from 'antd-mobile'
import { useAuthStore } from '@/app/cg06/store/useAuthStore'
import { useRouter } from 'next/navigation' 

const urlMap = {
  development: "https://api.zmetaport.com",
  dev: "https://dev-api.zmetaport.com",
  staging: "https://uat-api.zmetaport.com", 
  prod: "https://api.zmetaport.com",
};
const env = process.env.NEXT_PUBLIC_APP_ENV as
  | 'dev'
  | 'staging'
  | 'prod'

const envTest =
  typeof window !== 'undefined' &&
  (new URL(window.location.href).searchParams.get('env') as typeof env)

const envFinale = env == 'prod' ? env : envTest || env
console.log(envFinale, 'envFinale');
const url = urlMap[envFinale]
export { url as remote, envFinale, env }
export interface ResDataType<T = unknown> {
  code: string
  msg: string
  data?: T
  rows?: T
}

export type HTTP_METHOD = 'GET' | 'POST' | 'DELETE'

type Config = {
  tokenRequired: boolean,
  isHttpOrigin?: boolean
}

/**
 *
 * @param path /a/b/c
 * @returns res.data
 */
export function fetchWrapper<T = unknown>(
  path: string,
  data?: Record<string, unknown> | unknown[],
  method: HTTP_METHOD = 'GET',
  config?: Config
): Promise<T | undefined> {
  return fetchWithAuth<ResDataType<T>>(path, data, method, config).then(
    (r) => r.data || r.rows || r
  )
}

export function fetchWithAuth<T extends ResDataType>(
  path: string,
  data?: Record<string, unknown> | unknown[],
  method: 'GET' | 'POST' | 'DELETE' = 'GET',
  config?: Config
): Promise<T> {
  const store = useAuthStore.getState()
  const token = store.token
  const { tokenRequired = true, isHttpOrigin = false } = config || {}
  if (!token && tokenRequired) throw new Error('No Token')
  let realUrl = isHttpOrigin ? '' : url
  return fetch(realUrl + path, {
    headers: {
      Authorization: `Bearer ${token}`,
      ...(data ? { 'content-type': 'application/json' } : {}),
    },
    method,
    ...(data ? { body: JSON.stringify(data) } : {}),
  }).then((res) =>
    res.json().then((r) => {
      if (r.code != 200 && r.code != 0) {
        if (r.code == 401) {
          if (store.token && token === store.token) {
            store.setToken('')
            // window.location.href = process.env.NEXT_PUBLIC_APP_ENV === 'development' ? '/cg06/login' : '/cg06/login.html'
          }
          throw r
        }
        Toast.show(r.msg || '接口出错')
        throw r
      }
      return r as T
    })
  )
}

export function fetchWrapper2<T = unknown>(
  path: string,
  data?: Record<string, unknown> | unknown[],
  method: HTTP_METHOD = 'GET',
): Promise<T | undefined> {
  return fetchWithAuth2<ResDataType<T>>(path, data, method).then(
    (r) => r.data || r.rows
  )
}

export function fetchWithAuth2<T extends ResDataType>(
  path: string,
  data?: Record<string, unknown> | unknown[],
  method: 'GET' | 'POST' | 'DELETE' = 'GET',
): Promise<T> {
  // path 是 http 开头的直接请求
  const Url = !window.location.origin.includes('https') ? path : `https://screen.parceljet.com${path}`;

  return fetch(Url, {
    headers: {
      ...(data ? { 'content-type': 'application/json' } : {}),
    },
    method,
    ...(data ? { body: JSON.stringify(data) } : {}),
  }).then((res) =>
    res.json().then((r) => {
      if (r.code != 0) {
        Toast.show(r.msg || '接口出错');
        throw r;
      }
      return r as T;
    }),
  );
}